import { Directive, DirectiveBinding } from 'vue'
import * as echarts from 'echarts'
import { ChartResizer } from '../utils/chartResize'

/**
 * 自动调整图表大小的Vue指令
 * 
 * 使用方法: v-chart-resize:[chartId]="chartInstance"
 * 或者: v-chart-resize:[chartId]="{chart: chartInstance, options: chartOptions}"
 * 
 * 其中:
 * - chartId: 图表的唯一标识符，用于在ChartResizer中注册/注销
 * - chartInstance: 传入ECharts实例
 * - chartOptions: 可选，图表配置选项，用于初始化图表
 */
export const chartResize: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const chartId = binding.arg || `chart-${Math.random().toString(36).substring(2, 9)}`
    
    // 支持两种绑定值：直接传入chart实例或包含chart和options的对象
    let chartInstance: echarts.ECharts | null = null
    let options: echarts.EChartsOption | null = null
    
    if (binding.value && typeof binding.value === 'object') {
      if ('resize' in binding.value) {
        // 直接传入chart实例
        chartInstance = binding.value as echarts.ECharts
      } else if (binding.value.chart) {
        // 传入对象 {chart, options}
        chartInstance = binding.value.chart
        options = binding.value.options || null
      }
    }
    
    // 如果没有图表实例但有DOM元素，尝试初始化图表
    if (!chartInstance && el) {
      try {
        // 检查DOM元素是否有尺寸
        const { clientWidth, clientHeight } = el
        
        if (clientWidth > 0 && clientHeight > 0) {
          chartInstance = echarts.init(el)
          
          // 如果有提供options，设置图表选项
          if (options) {
            chartInstance.setOption(options)
          }
        } else {
          // DOM元素没有尺寸，使用MutationObserver监听尺寸变化
          const observer = new MutationObserver((mutations) => {
            const { clientWidth, clientHeight } = el
            if (clientWidth > 0 && clientHeight > 0) {
              observer.disconnect()
              chartInstance = echarts.init(el)
              
              // 如果有提供options，设置图表选项
              if (options) {
                chartInstance.setOption(options)
              }
              
              // 注册到ChartResizer
              if (chartInstance) {
                ChartResizer.getInstance().register(chartId, chartInstance, el)
              }
            }
          })
          
          observer.observe(el, {
            attributes: true,
            childList: true,
            subtree: true
          })
          
          // 5秒后如果还没有尺寸，停止观察
          setTimeout(() => {
            observer.disconnect()
          }, 5000)
        }
      } catch (error) {
        console.error('Failed to initialize chart:', error)
      }
    }
    
    // 注册到ChartResizer
    if (chartInstance) {
      ChartResizer.getInstance().register(chartId, chartInstance, el)
    }
  },
  
  beforeUnmount(el: HTMLElement, binding: DirectiveBinding) {
    const chartId = binding.arg || ''
    
    if (chartId) {
      ChartResizer.getInstance().unregister(chartId)
    }
  }
} 